﻿using Base.Core20;
using Base.Core20.Enums;
using Base.Core20.Flows;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;
using Winservice.demo.Business;
using Winservice.demo.Common;
using Winservice.demo.Models.Entities;

namespace Winservice.demo.Queue
{
    /// <summary>
    /// 队列任务处理
    /// </summary>
    public class QueueDoing
    {
        QueueManager queueManager = null;

        /// <summary>
        /// 队列任务处理-构造函数
        /// </summary>
        /// <param name="queueManager">queueManager</param>
        public QueueDoing(QueueManager queueManager)
        {
            this.queueManager = queueManager;
        }

        /// <summary>
        /// 开始处理
        /// </summary>
        /// <param name="queueManager">queueManager</param>
        public static void Start(QueueManager queueManager)
        {
            try
            {
                //参数：public delegate void ThreadStart(); 
                new Thread(new QueueDoing(queueManager).DoThreadFunc).Start();
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }

        /// <summary>
        /// 读取队列中的对象函数
        /// </summary>
        public async void DoThreadFunc()
        {
            TaskApproval_Business business = new TaskApproval_Business();
            QueueTask queueTask = null;
            string newIncident = "0";
            //无限循环读取，只要队列中有内容，这条线程就读出来
            while (true)
            {
                try
                {
                    //在队列中，是否有任务
                    if (this.queueManager.IsAvailable)
                    {
                        //有任务就开始处理
                        //1. 读【出】任务信息
                        queueTask = this.queueManager.GetQueueItem();

                        //2. 修改任务审批信息
                        int iResult_TaskApproval_QueueOut = await business.UpdateTaskApprovalStatusAsync(queueTask.FLOW_TASK_ID, FLOW_TASK_STATUS_Enum.QUEUE_OUT, string.Empty);

                        //Thread.Sleep(100); //处理一次就休息一下
                        if (iResult_TaskApproval_QueueOut <= 0)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(string.Format("TASK ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};FLOW_TASK_STATUS:{4};"
                                , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID
                                , FLOW_TASK_STATUS_Enum.QUEUE_OUT.GetHashCode()));

                            // 写出日志，帮助 后面 维护的时候，可以手动修改之
                            Logger2.CreateInstance().Write("任务出队列的维护"
                                  , MethodBase.GetCurrentMethod()
                                  , null
                                  , string.Format("任务出队列的异常({0})\r\nFLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}\r\nFLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}({6})", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY, FLOW_TASK_STATUS_Enum.QUEUE_OUT.GetHashCode()));

                            await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "任务出队列的维护");

                            continue;
                        }

                        // *** 先确认下当前节点是否是会签，如果是，则判断下 该会签节点(FLOW_COUNTERSIGN_FINISHED) 是否 已经结束，如果 结束，则不需要再次通讯，直接修改成 1033（代表系统自动办结）
                        if (queueTask.FIRST_SIGN_COUNT > 0)  // 先判断是否 会签，如果是 会签，则 去 验证 该会签节点是否 已经结束
                        {
                            var result_SignFinished = await business.GetSignFinished(queueTask);
                            if (result_SignFinished != null)
                            {
                                //代表 该会签节点 已经 处理结束，修改成 TASK_STATUS 1033（代表系统自动办结）
                                int iResult_TaskApproval_AutoEnd = await business.UpdateTaskApprovalStatusAsync(queueTask.FLOW_TASK_ID, FLOW_TASK_STATUS_Enum.AUTO_END, string.Empty);
                                if (iResult_TaskApproval_AutoEnd <= 0)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine(string.Format("TASK ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};FLOW_TASK_STATUS:{4};"
                                        , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID
                                        , FLOW_TASK_STATUS_Enum.AUTO_END.GetHashCode()));

                                    // 写出日志，帮助 后面 维护的时候，可以手动修改之
                                    Logger2.CreateInstance().Write("会签节点需要自动办结的维护"
                                          , MethodBase.GetCurrentMethod()
                                          , null
                                          , string.Format("会签节点需要自动办结的异常({0})\r\nFLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}\r\nFLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}({6})", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY, FLOW_TASK_STATUS_Enum.AUTO_END.GetHashCode()));

                                    await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "会签节点需要自动办结的维护");
                                }

                                Console.ForegroundColor = ConsoleColor.Blue;
                                Console.WriteLine(string.Format("TASK FINISHED ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};FLOW_TASK_STATUS:{4};"
                                    , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID
                                    , FLOW_TASK_STATUS_Enum.AUTO_END.GetHashCode()));

                                continue;
                            }
                        }

                        //3. 把 变量 序列化 对象
                        List<Variable> variableList = Utils.CreateInstance().GetVariables(queueTask.VARIABLES);

                        #region 这是 Ultimus 的 程序
                        /*
                        //4. 把 会签任务 序列化 对象
                        List<SignTask> signTaskList = Utils.CreateInstance().GetSignTasks(queueTask.SIGN_TASKS);

                        //5. 根据 会签任务、变量及意见 得到 新的变量 集合
                        bool isSignEndStep;
                        OPINION_Enum finalOpinion;
                        List<Var> newVariableList = Utils.CreateInstance().GetNewVariableList(queueTask, variableList, signTaskList, out isSignEndStep, out finalOpinion);
                        
                        if (isSignEndStep)
                        {
                            // 会签节点 结束
                            // 1. 把 IncidentID 及 SIGN_KEY 插入 FLOW_COUNTERSIGN_FINISHED
                            // 2. 再 根据 IncidentID 及 SIGN_KEY 把 FLOW_TASK_APPROVAL 中的 IS_CURRENT_SIGN_PATCH 修改 成 1
                            int iResult_SignStepIsFinished = await business.UpdateSignStepIsFinishedAsync(queueTask);
                            if (iResult_SignStepIsFinished <= 0)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(string.Format("COUNTERSIGN FINISHED ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};"
                                    , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID));

                                // 写出日志，帮助 后面 维护的时候，可以手动修改之
                                Logger2.CreateInstance().Write("会签节点需要结束的维护"
                                      , MethodBase.GetCurrentMethod()
                                      , null
                                      , string.Format("会签节点需要结束的异常({0})\r\nFLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}\r\nFLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(FLOW_COUNTERSIGN_FINISHED)", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY));

                                await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "会签节点需要结束的维护");

                                continue;
                            }
                        }
                        */
                        #endregion

                        #region 由服务进行 结束流程
                        //bool isIncidentFinished = false;
                        ////如果当前任务 是 最后一个 办结 节点，则需要 修改 FLOW_INCIDENT PROCESS_STATUS=103
                        //if (queueTask.IS_END_STEP == 0 && finalOpinion == OPINION_Enum.APPROVAL)  //不但是最后一个节点，而且还需要保证 是 非拒绝的（即，同意的节点）
                        //{
                        //    if (queueTask.FIRST_SIGN_COUNT > 0)  // 先判断是否 会签，如果是 会签，则 去 验证 该会签节点是否 已经结束
                        //    {
                        //        if (isSignEndStep)
                        //        {
                        //            isIncidentFinished = true;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        isIncidentFinished = true;
                        //    }
                        //}
                        //if (isIncidentFinished)
                        //{
                        //    int iResult_ProcessStatus_End = await business.UpdateIncidentStatusIsEndAsync(queueTask.FLOW_INCIDENT_ID, string.Empty);
                        //    if (iResult_ProcessStatus_End <= 0)
                        //    {
                        //        Console.ForegroundColor = ConsoleColor.Red;
                        //        Console.WriteLine(string.Format("INCIDENT ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};FLOW_INCIDENT_STATUS:{4};"
                        //            , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID
                        //            , FLOW_INCIDENT_STATUS_Enum.END.GetHashCode()));

                        //        // 写出日志，帮助 后面 维护的时候，可以手动修改之
                        //        Logger2.CreateInstance().Write("流程需要结束的维护"
                        //              , MethodBase.GetCurrentMethod()
                        //              , null
                        //              , string.Format("流程需要结束的异常({0})\r\nFLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}\r\nFLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(FLOW_INCIDENT_STATUS = {6})", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, queueTask.INCIDENT > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY, FLOW_INCIDENT_STATUS_Enum.END.GetHashCode()));

                        //        await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "流程需要结束的维护");

                        //        continue;
                        //    }

                        //    Console.ForegroundColor = ConsoleColor.Blue;
                        //    Console.WriteLine(string.Format("INCIDENT FINISHED ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};FLOW_INCIDENT_STATUS:{4};"
                        //        , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID
                        //        , FLOW_INCIDENT_STATUS_Enum.END.GetHashCode()));
                        //}
                        #endregion 由服务进行 结束流程

                        List<Var> newVariableList = new List<Var>();
                        variableList.ForEach(m =>
                        {
                            newVariableList.Add(new Var
                            {
                                VARIABLE_NAME = m.VARIABLE_NAME,
                                VARIABLE_VALUE = m.VARIABLE_VALUE
                            });

                        });

                        // ----
                        //6. 提交 A5 任务(利用 WebApi 来进行跟 A5 通讯)
                        //按钮类型（-1：无提交；1：申请提交；2：审批同意提交；3：审批退回上一步提交；4：退回发起人提交；5：终止流程提交（everyone）；）
                        string url = Utils.CreateInstance().GetAppConfig().A5_BASE_CORE_API + "/api/A5Flow/";
                        if (queueTask.BUTTON_TYPE == 1)
                        {
                            url += "StartProcessInstance";
                            var para = new
                            {
                                PROCESS_DEFINITION_ID = queueTask.PROCESS_DEFINITION_ID,
                                BUSINESS_KEY = queueTask.BUSINESS_KEY,
                                STARTER = queueTask.OPERATOR_GUID,
                                SUMMARY = queueTask.SUMMARY,
                                STR_VARIABLE = JsonConvert.SerializeObject(newVariableList),
                                USER_NAME = string.Empty,
                                PASS_WORD = string.Empty,
                                IS_LOG = false
                            };
                            string result_NewIncident = HttpClientHelper.PostResponse(url, para);
                            if (!string.IsNullOrEmpty(result_NewIncident))
                            {
                                newIncident = result_NewIncident.Replace("\"", string.Empty);
                            }
                            newIncident = string.IsNullOrEmpty(newIncident) ? "-999" : newIncident;
                            if (Convert.ToInt64(newIncident) <= 0)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(string.Format("GET NEW INCIDENT ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};"
                                    , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID));

                                // 代表 A5 提交失败
                                // 写出日志，帮助 后面 维护的时候，可以手动修改之
                                Logger2.CreateInstance().Write("A5提交(Button Type)的维护"
                                      , MethodBase.GetCurrentMethod()
                                      , null
                                      , string.Format(@"A5提交(Button Type)的异常({0})
FLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}
FLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(StartProcessInstance 事件的 失败:" + newIncident + ")", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY));

                                await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "A5提交(Button Type)的维护");

                                continue;
                            }
                        }
                        else if (queueTask.BUTTON_TYPE == 2)
                        {
                            url += "CompleteTask";
                            var para = new
                            {
                                TASK_ID = queueTask.TASK_ID,
                                COMMENTS = "",
                                STR_VARIABLE = JsonConvert.SerializeObject(newVariableList),
                                USER_NAME = string.Empty,
                                PASS_WORD = string.Empty,
                                IS_LOG = false
                            };
                            var result = HttpClientHelper.PostResponse(url, para);
                            ResultMessage r = JsonConvert.DeserializeObject<ResultMessage>(result);
                            if (!r.isSuccess.ToLower().Equals("true"))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(string.Format("CompleteTask ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};"
                                    , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID));

                                // 写出日志，帮助 后面 维护的时候，可以手动修改之
                                Logger2.CreateInstance().Write("A5提交(Button Type)的维护"
                                      , MethodBase.GetCurrentMethod()
                                      , null
                                      , string.Format(@"A5提交(Button Type)的异常({0})
FLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}
FLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(CompleteTask 事件的 失败:" + r.isSuccess.ToLower() + ")", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY));

                                await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "A5提交(Button Type)的维护");

                                continue;
                            }
                        }
                        else if (queueTask.BUTTON_TYPE == 3)
                        {
                            url += "RejectPrevActivity";
                            var para = new
                            {
                                TASK_ID = queueTask.TASK_ID,
                                COMMENTS = "",
                                USER_NAME = string.Empty,
                                PASS_WORD = string.Empty
                            };
                            var result = HttpClientHelper.PostResponse(url, para);
                            ResultMessage r = JsonConvert.DeserializeObject<ResultMessage>(result);
                            if (!r.isSuccess.ToLower().Equals("true"))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(string.Format("RejectPrevActivity ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};"
                                    , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID));

                                // 写出日志，帮助 后面 维护的时候，可以手动修改之
                                Logger2.CreateInstance().Write("A5提交(Button Type)的维护"
                                      , MethodBase.GetCurrentMethod()
                                      , null
                                      , string.Format(@"A5提交(Button Type)的异常({0})
FLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}
FLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(RejectPrevActivity 事件的 失败:" + r.isSuccess.ToLower() + ")", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY));

                                await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "A5提交(Button Type)的维护");

                                continue;
                            }
                        }
                        else if (queueTask.BUTTON_TYPE == 4)
                        {
                            url += "RejectStarterActivity";
                            var para = new
                            {
                                TASK_ID = queueTask.TASK_ID,
                                COMMENTS = "",
                                IS_BACK_RETURN = true,
                                USER_NAME = string.Empty,
                                PASS_WORD = string.Empty
                            };
                            var result = HttpClientHelper.PostResponse(url, para);
                            ResultMessage r = JsonConvert.DeserializeObject<ResultMessage>(result);
                            if (!r.isSuccess.ToLower().Equals("true"))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(string.Format("RejectStarterActivity ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};"
                                    , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID));

                                // 写出日志，帮助 后面 维护的时候，可以手动修改之
                                Logger2.CreateInstance().Write("A5提交(Button Type)的维护"
                                      , MethodBase.GetCurrentMethod()
                                      , null
                                      , string.Format(@"A5提交(Button Type)的异常({0})
FLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}
FLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(RejectStarterActivity 事件的 失败:" + r.isSuccess.ToLower() + ")", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY));

                                await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "A5提交(Button Type)的维护");

                                continue;
                            }
                        }
                        else if (queueTask.BUTTON_TYPE == 5)
                        {
                            url += "Suspension";
                            var para = new
                            {
                                INCIDENT = queueTask.INCIDENT,
                                USER_NAME = string.Empty,
                                PASS_WORD = string.Empty
                            };
                            var result = HttpClientHelper.PostResponse(url, para);
                            ResultMessage r = JsonConvert.DeserializeObject<ResultMessage>(result);
                            if (!r.isSuccess.ToLower().Equals("true"))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(string.Format("Suspension ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};"
                                    , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID));

                                // 写出日志，帮助 后面 维护的时候，可以手动修改之
                                Logger2.CreateInstance().Write("A5提交(Button Type)的维护"
                                      , MethodBase.GetCurrentMethod()
                                      , null
                                      , string.Format(@"A5提交(Button Type)的异常({0})
FLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}
FLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(Suspension 事件的 失败:" + r.isSuccess.ToLower() + ")", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY));

                                await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "A5提交(Button Type)的维护");

                                continue;
                            }
                            else
                            {
                                // 记录 日志
                                var result_LogAbort = await new TaskApproval_Business().LogAbortRecordAsync(new LOG_ABORTED()
                                {
                                    ID = Guid.NewGuid().ToString(),
                                    CREATE_DATE = DateTime.Now,
                                    CREATE_USER = queueTask.OPERATOR_ID,
                                    MODIFY_DATE = DateTime.Now,
                                    MODIFY_USER = queueTask.OPERATOR_ID,
                                    DEL_STATUS = 0,
                                    PROCESS_NAME = queueTask.PROCESS_NAME,
                                    INCIDENT = queueTask.INCIDENT,
                                    STEP_LABEL = queueTask.STEP_LABEL,
                                    COMMENTS = "",
                                    NOTES = "A5"
                                });

                            }
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(string.Format("BUTTON TYPE ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};"
                                , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID));

                            // 写出日志，帮助 后面 维护的时候，可以手动修改之
                            Logger2.CreateInstance().Write("A5提交(Button Type)的维护"
                                  , MethodBase.GetCurrentMethod()
                                  , null
                                  , string.Format(@"A5提交(Button Type)的异常({0})
FLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}
FLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(没有得到 合适的 Button Type)", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY));

                            await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "A5提交(Button Type)的维护");

                            continue;
                        }

                        //7. 修改当前任务的状态为 End
                        int iResult_TaskApproval_End = await business.UpdateTaskApprovalStatusAsync(queueTask.FLOW_TASK_ID, FLOW_TASK_STATUS_Enum.END, string.Empty);
                        if (iResult_TaskApproval_End <= 0)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(string.Format("TASK ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};FLOW_TASK_STATUS:{4};"
                                , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID
                                , FLOW_TASK_STATUS_Enum.END.GetHashCode()));

                            // 写出日志，帮助 后面 维护的时候，可以手动修改之
                            Logger2.CreateInstance().Write("任务End的维护"
                                  , MethodBase.GetCurrentMethod()
                                  , null
                                  , string.Format("任务End的异常({0})\r\nFLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}\r\nFLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}({6})", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY, FLOW_TASK_STATUS_Enum.END.GetHashCode()));

                            await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "任务End的维护");

                            continue;
                        }

                        //8. 重点：如果是任务的第一步提交时，一定要对T_Process表进行修改incident
                        if (Convert.ToInt64(queueTask.INCIDENT) <= 0)
                        {
                            if (Convert.ToInt64(newIncident) > 0)
                            {
                                int iResult_IncidentStatus = await business.UpdateIncidentNoAsync(queueTask.FLOW_INCIDENT_ID, newIncident.ToString(), string.Empty);

                                if (iResult_IncidentStatus <= 0)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine(string.Format("UPDATE INCIDENT ERROR ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};NEW INCIDENT:{4};"
                                        , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID
                                        , newIncident));

                                    // 写出日志，帮助 后面 维护的时候，可以手动修改之
                                    Logger2.CreateInstance().Write("申请时获得实例号的维护"
                                          , MethodBase.GetCurrentMethod()
                                          , null
                                          , string.Format("申请时获得实例号的异常({0})\r\nFLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}\r\nFLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(首次将实例号修改至业务主表的失败)", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY));

                                    await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "申请时获得实例号的维护");

                                    continue;
                                }
                            }
                        }
                        // ----

                        string inc = Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident;
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("===============================");
                        Console.WriteLine(queueTask.PROCESS_NAME + "(" + inc + ")[" + queueTask.STEP_LABEL + "](" + DateTime.Now.ToString() + ")");
                        Console.WriteLine("===============================");
                        Console.WriteLine();
                    }
                    Thread.Sleep(300); //处理一次就休息一下
                }
                catch (Exception ce)
                {
                    string msg = string.Format("申请时获得实例号的异常({0})\r\nFLOW_TASK_ID:{1}\r\nPROCESS_NAME:{2}\r\nINCIDENT:{3}\r\nFLOW_INCIDENT_ID:{4}\r\nCURRENT_STEP_KEY:{5}(异常)", DateTime.Now, queueTask.FLOW_TASK_ID, queueTask.PROCESS_NAME, Convert.ToInt64(queueTask.INCIDENT) > 0 ? queueTask.INCIDENT : newIncident, queueTask.FLOW_INCIDENT_ID, queueTask.CURRENT_STEP_KEY);

                    Logger2.CreateInstance().Write("A5_TaskSer_QueueDoing_Error"
                          , MethodBase.GetCurrentMethod()
                          , ce, msg);

                    await business.UpdateStatusIsExceptionAsync(queueTask.FLOW_INCIDENT_ID, queueTask.FLOW_TASK_ID, "队列异常:" + msg);

                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(string.Format("TASK EXCEPTION ---- PROCESS_NAME:{0}({1});FLOW_INCIDENT_ID:{2};TASK_ID:{3};"
                        , queueTask.PROCESS_NAME, queueTask.INCIDENT, queueTask.FLOW_INCIDENT_ID, queueTask.TASK_ID));

                    Thread.Sleep(300); //处理一次就休息一下
                }
            }
        }
    }
}
